package com.gzone.contentprovider;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;

import com.gzone.contentprovider.adapter.ItemListAdapter;
import com.gzone.contentprovider.sql.dao.CategoryDAO;
import com.gzone.contentprovider.sql.dao.ItemDAO;
import com.gzone.contentprovider.sql.model.Category;
import com.gzone.contentprovider.sql.model.Item;
import com.gzone.contentprovider.sql.service.DatabaseServices;
import com.gzone.contentprovider.utils.HTTPClientUtil;
import com.gzone.contentprovider.utils.IOUtil;

import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.widget.AbsListView;
import android.widget.ListView;
import android.widget.TextView;

public class ItemListScreen extends Activity {
	private static final String TAG = "ItemListScreen";
	private static final int NULL_VALUE = -1;
	private DatabaseServices ds;
	private int catId;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.screen_item_list);
		catId = NULL_VALUE;
		try{
			catId = getIntent().getIntExtra("CategoryId", NULL_VALUE);
		}catch (Exception e) {
			e.printStackTrace();
		}
		ds = DatabaseServices.getInstance(this);
		
//		updateDB();
		
		ListView listView = (ListView) findViewById(R.id.list_view);
		listView.setTranscriptMode(AbsListView.TRANSCRIPT_MODE_DISABLED);
		ArrayList<Item> items = null;
		if(catId == NULL_VALUE){
			items = ds.getAllItem();
		}else{
			items = ds.getItemDAO().findByParameter(ItemDAO.CATEGORY_ID, catId);
		}
		
		ItemListAdapter adapter = new ItemListAdapter(this, items );
		listView.setAdapter(adapter);
		TextView tvCategoryTitle = (TextView) findViewById(R.id.textview_category_title);
		tvCategoryTitle.setText(ds.getCategoryDAO().findById(catId).title);
	}
	
	

	private void updateDB() {
		// TODO Auto-generated method stub
		String dataItem = "";
//		try {
//			InputStream is = this.getAssets().open("json.txt");
//			dataItem = IOUtil.getStreamContentAsString(is, "UTF-8");
//		} catch (IOException e1) {
//			// TODO Auto-generated catch block
//			e1.printStackTrace();
//		} catch (Exception e) {
//			// TODO Auto-generated catch block
//			e.printStackTrace();
//		}
		String url = "http://91.121.156.153/~services/json.php?op=g&t=item";
		try {
			dataItem  = HTTPClientUtil.getString(url);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		dataItem = dataItem.trim();
		if(dataItem.endsWith(";")){
			dataItem = dataItem.substring(0, dataItem.length()-1);
		}
		dataItem = dataItem.replaceAll("\n", " ");
		dataItem = dataItem.replace("\r", " ");
		Log.i(TAG, "--->" + dataItem);
		ds.synchronizeItem(dataItem);
	}
}
